package com.lingnan.tijian.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lingnan.tijian.constant.JwtClaimsConstant;
import com.lingnan.tijian.constant.MessageConstant;
import com.lingnan.tijian.domain.User;
import com.lingnan.tijian.domain.dto.UserLoginDTO;
import com.lingnan.tijian.domain.vo.UserLoginVO;
import com.lingnan.tijian.exception.AccountNotFoundException;
import com.lingnan.tijian.exception.BaseException;
import com.lingnan.tijian.exception.PasswordErrorException;
import com.lingnan.tijian.mapper.UserMapper;
import com.lingnan.tijian.properties.JwtProperties;
import com.lingnan.tijian.service.IUserService;
import com.lingnan.tijian.utils.JwtUtil;
import com.lingnan.tijian.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.security.auth.login.AccountLockedException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper,User> implements IUserService
{
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private JwtProperties jwtProperties;

    /**
     * 新增用户
     * @param user 无
     * @return
     */
    @Override
    public boolean insertUser(User user)
    {
        //1.判断是否重名
        List<User> list = lambdaQuery()
                .eq(User::getUserId, user.getUserId())
                .list();
        if (!list.isEmpty()) {
            throw new BaseException("该手机号已存在");
        }
        // 设置默认的 userType 为 1
        user.setUserType(1L);
        user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
        System.out.println(user.getPassword());
        // 插入数据
        return save(user);
    }

    @Override
    public UserLoginVO login(UserLoginDTO userLoginDTO) {
        //1、根据用户名查询数据库中的数据
        User loginUser= this.lambdaQuery()
                .eq(User::getUserId, userLoginDTO.getUserId())
                .one();
        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if(loginUser==null){
            throw new BaseException(MessageConstant.ACCOUNT_NOT_FOUND);
        }
        //密码比对
        //对前端传入的密码进行md5加密
        String password= DigestUtils.md5DigestAsHex(userLoginDTO.getPassword().getBytes());
//        String password=userLoginDTO.getPassword();
        User user = lambdaQuery()
                .eq(User::getUserId, userLoginDTO.getUserId())
                .eq(User::getPassword, password)
                .select(User::getPassword)
                .one();
        if (!password.equals(user.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }
        //登录成功后，生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID, loginUser.getUserId());
        claims.put(JwtClaimsConstant.SEX, loginUser.getSex());
        String token = JwtUtil.createJWT(
                jwtProperties.getAdminSecretKey(),
                jwtProperties.getAdminTtl(),
                claims);
        //3、返回数据
        UserLoginVO userLoginVO = UserLoginVO.builder()
                .id(Long.valueOf(loginUser.getUserId()))
                .token(token)
                .build();
        return userLoginVO;
    }

    @Override
    public User selectUserById() {
        Map<String, Object> map= ThreadLocalUtil.get();
        String userId = (String)map.get("userId");
        return getById(userId);
    }
}
